package com.tfb.web.controller;

import java.util.Locale;

import javax.servlet.http.HttpServletRequest;

public class HeaderNetInfo {
	private String language;
	private String addr;
	private int portNum;
	private boolean isSecure;
	private boolean keepAlive;
	private String contextPath;
	private String requestURL;
	private String requestURI;
	private HttpServletRequest req;

	public HeaderNetInfo(HttpServletRequest req) {
		try {

			this.req = req;

			this.addr = getIP(req);
			this.portNum = getPort(req);

			this.isSecure = req.isSecure();
			this.keepAlive = keepAlive();
			this.contextPath = req.getContextPath();
			this.requestURL = req.getRequestURL().toString();
			this.requestURI = req.getRequestURI();

			this.language = getAcceptLanguage();
		} catch (Exception e) {

		}
	}

	public HeaderNetInfo() {

	}

	private String getIP(HttpServletRequest req) {
		String ip = req.getHeader("CLIENT_IP");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = req.getHeader("x-forwarded-for");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = req.getRemoteAddr();
		}
		if (ip != null && ip.indexOf(',') != -1) {
			ip = ip.substring(0, ip.indexOf(',')).trim();
		}

		return ip;
	}

	public String getIPAddr() {
		return this.addr;
	}

	public int getPort(HttpServletRequest req) {
		String port = req.getHeader("host");
		int portNumber;
		boolean isIPv6 = false;
		if (port != null) {
			int nstart = port.indexOf(':');
			int nend = port.indexOf(']');
			if (nstart > 0 && nend > 0 && nstart < nend && port.contains("[") && port.contains("]")) {
				isIPv6 = true;
			}
		}
		if (isIPv6 && (portNumber = port.indexOf("]:")) > 0) {
			return Integer.parseInt(port.substring(portNumber + 2));
		} else if (!isIPv6 && (portNumber = port.indexOf(":")) > 0) {
			return Integer.parseInt(port.substring(portNumber + 1));
		}

		return Integer.parseInt(port);
	}

	private boolean keepAlive() {
		String connectionHdr = req.getHeader("Connection");

		if (connectionHdr == null) {
			String protocol = req.getProtocol();
			return protocol != null && protocol.compareToIgnoreCase("HTTP/1.1") == 0;
			// absence of Connection: header means assume keep-alive, this is
			// only true for HTTP 1.1
		}

		return (connectionHdr.compareToIgnoreCase("Keep-Alive") == 0);
	}

	private String getAcceptLanguage() {
		String sLang = "";
		return sLang;
	}

	public String getContextPath() {
		return this.contextPath;
	}

	public boolean getIsSecure() {
		return this.isSecure;
	}

	public boolean getKeepAlive() {
		return this.keepAlive;
	}

	public int getPortNum() {
		return this.portNum;
	}

	public HttpServletRequest getReq() {
		return this.req;
	}

	public String getRequestURL() {
		return this.requestURL;
	}

	public String getRequestURI() {
		return this.requestURI;
	}

	public String getLanguage() {
		return language;
	}
}
